
import 'package:flutter/widgets.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../../constants.dart';
import '../../repository/api.dart';
import '../../repository/dto/auth_dto.dart';
import '../../utils/sp_utils.dart';

class AuthViewModel with ChangeNotifier {
  RegisterInfo registerInfo = RegisterInfo();
  LoginInfo loginInfo = LoginInfo();

  Future<bool?> register() async {
    if (registerInfo.username == null || registerInfo.password == null || registerInfo.repassword == null) {
      Fluttertoast.showToast(msg: '请输入用户名、密码、确认密码');
      return false;
    }
    if (registerInfo.password != registerInfo.repassword) {
      return Fluttertoast.showToast(msg: '两次输入密码不一致');
    }
    // 注册逻辑
    return await Api.instance.register(registerInfo.username!, registerInfo.password!, registerInfo.repassword!);
  }

  Future<bool?> login() async {
    if (loginInfo.username == null || loginInfo.password == null) {
      Fluttertoast.showToast(msg: '请输入用户名、密码');
      return false;
    }
    // 登录逻辑
    AuthData? authData = await Api.instance.login(loginInfo.username!, loginInfo.password!);
    if(authData == null) {
      return false;
    }
    // 登录成功后，将用户信息存储到本地
    await SpUtils.putStorage(Constants.USERNAME, authData.username);
    return true;
  }

  Future<bool?> logout() async {
    // 退出登录逻辑
    await Api.instance.logout();
    // 退出登录后，清除本地存储的用户信息
    await SpUtils.removeAll();
    return true;
  }
}

class LoginInfo {
  String? username;
  String? password;
}

class RegisterInfo {
  String? username;
  String? password;
  String? repassword;
}
